package com.jia.together.controller;


import com.jia.together.entity.Member;
import com.jia.together.service.MemberService;
import com.jia.together.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dujiajia
 * @since 2021-02-19
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MemberService memberService;

    @GetMapping("/list")
    public R list(@RequestParam Long pageNum,@RequestParam Long pageSize) {
        Map<String,Object> map = memberService.selectPageList(pageNum,pageSize);
        return R.ok().data(map);
    }
    @GetMapping("/info/{id}")
    public R info(@PathVariable String id){
        Member byId = memberService.getById(id);
        return R.ok().data("data",byId);
    }
    @PostMapping("/add")
    public R add(@RequestBody Member member){
        String password = member.getPassword();
        String newPassword = passwordEncoder.encode(password);
        Member saveMember = new Member();
        BeanUtils.copyProperties(member,saveMember);
        saveMember.setPassword(newPassword);
        memberService.save(saveMember);
        return R.ok();
    }
    @PutMapping("/update")
    public R update(@RequestBody Member member){
        String password = member.getPassword();
        String newPassword = passwordEncoder.encode(password);
        Member saveMember = new Member();
        BeanUtils.copyProperties(member,saveMember);
        saveMember.setPassword(newPassword);
        memberService.updateById(saveMember);
        return R.ok();
    }
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable String id){
        memberService.removeById(id);
        return R.ok();
    }
}

